package edu.zut.main.thread;

public class ThreadCommunication {

    public static void main(String[] args) {
        Storehouse storehouse = new Storehouse();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                char c = (char) (Math.random()*26 + 'a');
                storehouse.push(c);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者").start();

        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                storehouse.pop();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者").start();
    }
}
//以生产者消费者模式模拟线程通信
class Storehouse{

    //指定仓库的长度
    private char[] data = new char[5];
    //模拟下标的移动
    int point = 0;

    //生产  要保证它是安全的
    public synchronized void push(char c){

        while (point == data.length){
            //如果库存满了，让生产操作进入等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //唤醒正在等待的消费者
        notify();
        data[point] = c;
        System.out.println("生产了：" + data[point]);
        point++;
    }

    //被消费   保证安全
    public synchronized void pop(){
        while (point == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //唤醒等待的生产者
        notifyAll();
        point--;
        System.out.println("消费了：" + data[point]);
    }




}


